package cn.zld.sh.sh.base;

import android.app.Service;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cn.zld.sh.sh.R;
import cn.zld.sh.sh.ui.userfragment.UserFragment;
import cn.zld.sh.sh.util.LogUtils;
import cn.zld.sh.sh.util.SharedUtils;
import cn.zld.sh.sh.util.ToastUtils;

public class BaseFragment extends Fragment {

    protected Context myContext;
    private Vibrator vibrator;
    private MediaPlayer mediaPlayer;
    protected String userAgent;

    private boolean mediaPlaying = false;
    protected Handler handler = new Handler();
    protected boolean playVoice = false;


    private int count = 0;

    protected String[] userAgents = new String[]{
            "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; PE-TL20 Build/HuaweiPE-TL20) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.3 Mobile Safari/537.36",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
            "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
            "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.4.994 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.6.4.950 UWS/2.11.1.50 Mobile Safari/537.36 AliApp(DingTalk/4.5.8) com.alibaba.android.rimet/10380049 Channel/227200 language/zh-CN",
            "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; EML-AL00 Build/HUAWEIEML-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.9.4.974 UWS/2.13.1.48 Mobile Safari/537.36 AliApp(DingTalk/4.5.11) com.alibaba.android.rimet/10487439 Channel/227200 language/zh-CN",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; BAC-AL00 Build/HUAWEIBAC-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.9.4.974 UWS/2.13.1.48 Mobile Safari/537.36 AliApp(DingTalk/4.5.11) com.alibaba.android.rimet/10487439 Channel/227200 language/zh-CN",
            "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.9.4.974 UWS/2.13.1.48 Mobile Safari/537.36 AliApp(DingTalk/4.5.11) com.alibaba.android.rimet/10487439 Channel/227200 language/zh-CN",
            "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; vivo Y85 Build/OPM1.171019.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.9.6.976 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; BLN-AL40 Build/HONORBLN-AL40) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.3.993 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; VTR-AL00 Build/HUAWEIVTR-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.4.994 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 5.1.1; zh-CN; SM-J3109 Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.8.0.960 UWS/2.12.1.18 Mobile Safari/537.36 AliApp(TB/7.5.4) UCBS/2.11.1.1 WindVane/8.3.0 720X1280",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; MI 5 Build/OPR1.170623.032) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.8.9.969 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 5.1; zh-CN; vivo X6Plus D Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.8.0.960 UWS/2.12.1.22 Mobile Safari/537.36 AliApp(TB/7.6.4) UCBS/2.11.1.1 WindVane/8.3.0 1080X1920",
            "Mozilla/5.0 (Linux; U; Android 5.1.1; zh-CN; OPPO R9 Plusm A Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.4.994 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 7.1.2; zh-CN; Redmi 5 Plus Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.4.994 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 7.1.1; zh-CN; OD105 Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.3.993 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; COL-TL10 Build/HUAWEICOL-TL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.1.3.993 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-CN; MIX 2S Build/OPR1.170623.032) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.9.4.974 UWS/2.14.0.7 Mobile Safari/537.36 AliApp(TB/7.9.0) UCBS/2.11.1.1 TTID/10005934@taobao_android_7.9.0 WindVane/8.3.0 1080X2030",
            "Mozilla/5.0 (Linux; U; Android 5.1.1; zh-CN; vivo X7 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/11.6.4.950 UCBS/2.11.1.20 Mobile Safari/537.36 AliApp(TB/7.0.2) WindVane/8.0.0 1080X1920",
    };


    protected void setUserAgent(){
        String agent = SharedUtils.getString("curUserAgent");
        if(agent != null && !agent.isEmpty()){
            userAgent = agent;
            return;
        }
        agent = userAgents[(int)(Math.random()*(userAgents.length-1))];
        SharedUtils.putString("curUserAgent", agent);
        userAgent = agent;
    }

    protected String ToasterMsg;

    protected void Toaster(String msg){
        ToasterMsg = msg;
        handler.post(ToaseterTask);
    }

    private Runnable ToaseterTask = new Runnable() {
        @Override
        public void run() {
            ToastUtils.showLongToast(myContext, ToasterMsg);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        myContext = getContext();
        playVoice = SharedUtils.getBoolean(getString(R.string.setting_switch_voice));
        setUserAgent();
        checkLogin();
//        vibrator=(Vibrator)myContext.getSystemService(Service.VIBRATOR_SERVICE);
        mediaPlayer=new MediaPlayer();
        super.onActivityCreated(savedInstanceState);
    }

    private void checkLogin(){
        new Thread(){
            public void run(){
                try {

                    Thread.sleep(120000);
//                    Thread.sleep(5000);
                    if(SharedUtils.getString("token") != null && !SharedUtils.getString("token").isEmpty()){
                        new UserFragment().getUinfo(false);
                    }
                    checkLogin();
                }catch (Exception e){
                    return;
                }
            }
        }.start();
    }


    /**
     * 震动功能
     * @param milliseconds 震动时长 单位为毫秒
     */
    private void Vibrate(long milliseconds){

//		long [] pattern={100,400,100,400};//停止 开启  停止 开启
//		vibrator.vibrate(pattern, 2);//重复两次上面的panttern，如果只是震动一次，index的值设定为-1
        vibrator.vibrate(milliseconds);
    }
    /**
     * 震动功能
     * @param pattern 自定义震动（模式）周期 long[] pattern={100,400,100,400}//停止 开启 停止 开启
     * @param isRepeat
     */
    private void Vibrate(long[] pattern,boolean isRepeat){
        vibrator.vibrate(pattern, isRepeat?1:-1);
    }
    /**
     * 停止震动与响铃
     */
    protected void destroy(){
        if(mediaPlaying){
//            vibrator.cancel();
            mediaPlayer.stop();//停止
//            mediaPlayer.release();//释放资源
        }
        mediaPlaying = false;
    }

    /**
     * 提示音
     * @param mp3 要播放的音乐资源
     */
    protected void playvoid(int mp3){
//        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) ;
//        Ringtone mRingtone = RingtoneManager.getRingtone(this,uri);
//        mRingtone.play();
        LogUtils.i("play_voice", "start play");
        mediaPlaying = true;
        try{
            mediaPlayer.reset();
            mediaPlayer.setLooping(false);//重复播放
            Uri uri = null;
//            uri=Uri.parse("http://app.jubaosuoping.com/sh/mp3/qdm.mp3");//raw文件夹下的yes音频文件，使用的时候要注意修改
            uri=Uri.parse("android.resource://" + myContext.getPackageName() + "/"+mp3);//raw文件夹下的yes音频文件，使用的时候要注意修改
//            uri=Uri.parse("android.resource://" + myContext.getPackageName() + "/"+mp3 + ".mp3");//raw文件夹下的yes音频文件，使用的时候要注意修改

            LogUtils.i("play_voice", uri.toString());
            //mediaPlayer.create(MainActivity.this, R.raw.yes);
            mediaPlayer.setDataSource(myContext, uri);//设置文件员
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
            mediaPlayer.prepare();//添加缓存
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();//开始播放
                }
            });
            long[] longg = {2000 , 100};
//            Vibrate(longg, false);
            count = 0;
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.start();//开始播放
                    LogUtils.i("play_voice", count + "");
                    long[] longg = {2000, 100};
//                    Vibrate(longg, false);

                    if(count >= 6){
//                        vibrator.cancel();
                        destroy();
                    }
                    count++;
                }
            });
        }catch (Exception e) {
            LogUtils.i("play_voice", "play_voice_exception" + e.toString());
            mediaPlaying = false;

            // TODO: handle exception
        }
    }
}
